
package com.why.blog.aop;

import com.why.blog.bean.RequsetLog;
import com.why.blog.dao.requestSave;
import com.why.blog.utils.IpToAddressUtil;
import com.why.blog.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @program: blog
 * @description:
 * @author: @why
 * @create: 2020-10-05 14:16
 **/
//声明这个类要切东西
@Aspect
@Component
public class logAop {
    //打印出日志信息所在的类
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private RequsetLog requsetLog;
    @Autowired
    private com.why.blog.dao.requestSave requestSave;
    @Autowired
    public void setRequsetLog(RequsetLog requsetLog) {
        this.requsetLog = requsetLog;
    }
    //设置切入点
    @Pointcut("execution(* com.why.blog.controller.*.*(..))")
    public void log() {}
    //方法执行前，将用户的所有信息进行收集
    @Before("log()")
    public void doBefore(JoinPoint point) {

        //从spring框架中获取请求上下文，得到请求的各种东西
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //得到请求
        HttpServletRequest request = attributes.getRequest();
        //设置对应的信息
        requsetLog.setURL(request.getRequestURL().toString());
        requsetLog.setIp(request.getRemoteAddr());
        //得到类的类型和调用的类的方法
        requsetLog.setClassMethod(point.getSignature().getDeclaringTypeName()+".."+point.getSignature().getName());
        //得到方法的参数
        requsetLog.setArgs(point.getArgs());
        //查看访问者ip
        String ip = IpUtil.getIpAddr(request);
        if(requestSave.checkIp(ip)==null)
        {
            requsetLog.setIp(ip);
            //保存访问者地理位置
            requsetLog.setLocation(IpToAddressUtil.getCityInfo(ip));
            requestSave.saveIp(requsetLog);
        }
        // System.out.println(requsetLog);
        logger.info(requsetLog.toString());
        logger.info("dobefoe");
    }

//    @After("log()")
//    public void doAfter() {
//        // logger.info("after");
//    }

//    @AfterReturning(pointcut = "log()", returning = "result")
//    public void whenReturning(Object result) {
//    }
}
